package service

import (
	"gin-mi/config"
	"gin-mi/handler/request"
	"gin-mi/model"
	"gin-mi/pkg"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Register(c *gin.Context) {
	var form request.Register
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var user model.User
	if err := user.GetUserByPhone(config.DB, form.Phone); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "注册失败",
		})
		return
	}
	if user.ID > 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "账号已存在",
		})
		return
	}
	user.Username = form.Username
	user.Password = pkg.MD5(form.Password)
	user.Phone = form.Phone
	if err := user.AddUser(config.DB); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func Login(c *gin.Context) {
	var form request.Register
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 404,
			"msg":  "参数错误",
		})
		return
	}
	var user model.User
	if err := user.GetUserByPhone(config.DB, form.Phone); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 404,
			"msg":  "注册失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 404,
			"msg":  "账号不存在",
		})
		return
	}
	if pkg.MD5(form.Password) != user.Password {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 404,
			"msg":  "密码错误",
		})
		return
	}
	token, _ := pkg.GetJwtToken(int(user.ID))
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": gin.H{
			"token": token,
		},
	})
}
func Black(c *gin.Context) {

}
func Friend(c *gin.Context) {

}
